package com.bolinfest.editor;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.http.AuthSubUtil;
import com.google.gdata.util.AuthenticationException;

public class AuthSubFilter implements Filter {

  private UserService userService = UserServiceFactory.getUserService();

  @Override
  public void doFilter(ServletRequest servletRequest,
      ServletResponse servletResponse,
      FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest)servletRequest;
    HttpServletResponse resp = (HttpServletResponse)servletResponse;

    User user = userService.getCurrentUser();
    if (user == null) {
      resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
      return;
    }

    String sessionToken = TokenStore.getToken(user);
    if (sessionToken == null) {
      // Perhaps the user has been redirected to this URL from the AuthSub URL.
      // If so, this request should contain the token.
      String queryString = req.getQueryString();
      String authToken = null;
      if (queryString != null) {
        authToken = AuthSubUtil.getTokenFromReply(queryString);
      }
      if (authToken == null) {
        String nextUrl = req.getRequestURL().toString();
        final boolean secure = false;
        final boolean session = true;
        String requestUrl = AuthSubUtil.getRequestUrl(
            nextUrl,
            "http://docs.google.com/feeds/ https://docs.google.com/feeds/",
            secure,
            session);
        resp.sendRedirect(requestUrl);
        return;
      } else {
        // Upgrade the single-use token to a multi-use session token.
        try {
          final PrivateKey privateKey = null;
          sessionToken = AuthSubUtil.exchangeForSessionToken(authToken, privateKey);
          TokenStore.addToken(user, sessionToken);
          // TODO: Redirect to the same URL without the "token" query parameter.
        } catch (AuthenticationException e) {
          // TODO: Inform the user.
          return;
        } catch (GeneralSecurityException e) {
          // TODO: Inform the user.
          return;
        }
      }
    }
    if (sessionToken == null) {
      throw new IllegalStateException("sessionToken should not be null here");
    }

    filterChain.doFilter(req, resp);
  }

  @Override
  public void destroy() {
  }

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
  }

}
